package com.easpeed.user.utils.zxing;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;


import com.blankj.utilcode.util.LogUtils;
import com.easpeed.elevator.R;
import com.easpeed.user.utils.zxing.android.BeepManager;
import com.easpeed.user.utils.zxing.android.CaptureActivityHandler;
import com.easpeed.user.utils.zxing.android.FinishListener;
import com.easpeed.user.utils.zxing.android.InactivityTimer;
import com.easpeed.user.utils.zxing.bean.ZxingConfig;
import com.easpeed.user.utils.zxing.camera.CameraManager;
import com.easpeed.user.utils.zxing.common.Constant;
import com.easpeed.user.utils.zxing.decode.DecodeImgCallback;
import com.easpeed.user.utils.zxing.decode.DecodeImgThread;
import com.easpeed.user.utils.zxing.decode.ImageUtil;
import com.easpeed.user.utils.zxing.view.ScanView;
import com.gyf.immersionbar.ImmersionBar;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ScanCaptureActivity extends CaptureAbstractActivity implements SurfaceHolder.Callback, View.OnClickListener {


    private SurfaceView previewView;
    private ScanView viewfinderView;
    private Unbinder bind;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private SurfaceHolder surfaceHolder;

    @Override
    public ScanView getScanView() {
        return viewfinderView;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }


    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .statusBarDarkFont(false) // 设置状态栏字体为深色
                .transparentStatusBar()  // 透明状态栏
                .fitsSystemWindows(true)
                .statusBarColor(R.color.colorTitleBar)
                .init();
//        setTheme(R.style.ActivityAnimTheme);
        // 保持Activity处于唤醒状态
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        /*先获取配置信息*/
        try {
            config = (ZxingConfig) getIntent().getExtras().get(Constant.INTENT_ZXING_CONFIG);
        } catch (Exception e) {
            LogUtils.e("config:" + e.toString());
        }
        if (config == null) {
            config = new ZxingConfig();
        }
        setContentView(R.layout.activity_scan_capture);
        bind = ButterKnife.bind(this);

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initView();
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        beepManager.setPlayBeep(config.isPlayBeep());
        beepManager.setVibrate(config.isShake());
    }


    private void initView() {
        previewView = findViewById(R.id.preview_view);
        previewView.setOnClickListener(this);
        viewfinderView = findViewById(R.id.viewfinder_view);
        viewfinderView.setZxingConfig(config);
//        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
//        StatusBarUtil.setTranslucentStatus(this);  /*设置状态栏透明*/
//        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
//            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
//            //这样半透明+白=灰, 状态栏的文字能看得清
//            StatusBarUtil.setStatusBarColor(this, 0x55000000);
//        }
//        StatusBarUtil.setStatusBarColor(this, getResources().getColor(R.color.white));
//        ToolBarManager toolBarManager = new ToolBarManager(this, mToolbar);
//        toolBarManager.showBackIcon(true);
//        toolBarManager.setTitle(getResources().getString(R.string.rs100464));
    }


    /**
     * @param rawResult 返回的扫描结果
     */
    @Override
    public void handleDecode(String rawResult) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        Intent intent = getIntent();
        intent.putExtra(Constant.CODED_CONTENT, rawResult);
        setResult(RESULT_OK, intent);
        this.finish();
    }

    @Override
    public void switchFlashImg(int flashState) {

    }


    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication(), config);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;
        surfaceHolder = previewView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            // 重置callback，等待surfaceCreated()来初始化camera
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager);
            }
        } catch (IOException ioe) {
            LogUtils.e(ioe.getMessage());
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            LogUtils.e("Unexpected error initializing camera" + e.getMessage());
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("扫一扫");
//        builder.setMessage(getString(R.string.lcs_scan_msg_camera_framework_bug));
//        builder.setPositiveButton(R.string.lcs_scan_button_ok, new FinishListener(this));
//        builder.setOnCancelListener(new FinishListener(this));
//        builder.show();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();

        if (!hasSurface) {

            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
        if (bind != null) {
            bind.unbind();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.flashLightLayout) {
            /*切换闪光灯*/
            cameraManager.switchFlashLight(handler);
        } else if (id == R.id.albumLayout) {
            /*打开相册*/
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, Constant.REQUEST_IMAGE);
        } else if (id == R.id.backIv) {
            finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_IMAGE && resultCode == RESULT_OK) {
            String path = ImageUtil.getImageAbsolutePath(this, data.getData());
            new DecodeImgThread(path, new DecodeImgCallback() {
                @Override
                public void onImageDecodeSuccess(String result) {
                    handleDecode(result);
                }

                @Override
                public void onImageDecodeFailed() {
                    LogUtils.e("抱歉，解析失败,换个图片试试.");
                }
            }).run();
        }
    }
}
